package com.zongzi.stock.module;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.orhanobut.logger.Logger;
import com.zongzi.stock.R;
import com.zongzi.stock.bean.DailyDataBean;
import com.zongzi.stock.bean.SearchResultBean;
import com.zongzi.stock.global.URLs;
import com.zongzi.stock.module.stockdetail.StockDetailActivity;
import com.zongzi.stock.utils.SharePreferenceUtils;
import com.zongzi.stock.utils.TimeUtils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

public class HomeActivity extends AppCompatActivity {


    @BindView(R.id.et_stock_num)
    EditText mEtStockNum;
    @BindView(R.id.rv_stock)
    RecyclerView mRvStock;
    @BindView(R.id.rv_search)
    RecyclerView mRvSearch;

    public static final String ERROR_MSG = "SUCCESS";
    public static final String STOCK_NUM = "stockNum";
    public static final String STOCK_NAME = "stockName";
    //上证指数代码:sh000001
    public static final String SZZU = "sh000001";
    //间隔多久获取一次数据ms
    public static final int TIMER_INTERVAL = 30 * 100;
    //HANDL_MSG_UPDATA = 0, 更新数据
    public static final int HANDL_MSG_UPDATA = 0;


    private Gson gson = new Gson();
    private SearchResultBean mSearchResultBean;
    private SearchAdapter mSearchAdapter;

    private DailyDataBean mDailyDataBean;
    private StockListAdapter mStockListAdapter;

    private List<String> stockNums;

    // long currentMillis;

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case HANDL_MSG_UPDATA:
                    updateData();
                    break;

                default:
                    break;
            }
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        ButterKnife.bind(this);

        mHandler.sendEmptyMessage(HANDL_MSG_UPDATA);

        stockNums = SharePreferenceUtils.getStringList(STOCK_NUM, HomeActivity.this);
        mDailyDataBean = new DailyDataBean();
        mDailyDataBean.data = new ArrayList<>();

        mRvSearch.setLayoutManager(new LinearLayoutManager(HomeActivity.this));
        mRvSearch.addItemDecoration(new DividerItemDecoration(HomeActivity.this,
                DividerItemDecoration.VERTICAL));

        mRvStock.setLayoutManager(new LinearLayoutManager(HomeActivity.this));
        mRvStock.addItemDecoration(new DividerItemDecoration(HomeActivity.this,
                DividerItemDecoration.VERTICAL));

        ItemDragHelperCallback callback = new ItemDragHelperCallback();
        callback.setOnItemDragListener(new ItemDragHelperCallback.OnItemDragListener() {
            @Override
            public void onSwipe(int position) {
                removeStockNum(position);
            }
        });
        ItemTouchHelper touchHelper = new ItemTouchHelper(callback);
        touchHelper.attachToRecyclerView(mRvStock);

        mEtStockNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if ((mEtStockNum.getText() + "").equals("")) {
                    mRvSearch.setVisibility(View.GONE);
                    return;
                }
                mRvSearch.setVisibility(View.VISIBLE);
                //搜索的时候，输入改变就请求一次
                Logger.d("afterTextChanged:" + mEtStockNum.getText());
                try {
                    Logger.d(URLs.searchStock(mEtStockNum.getText() + ""));
                    OkGo.get(URLs.searchStock(mEtStockNum.getText() + ""))     // 请求方式和请求url
                            .tag(this)                       // 请求的 tag, 主要用于取消对应的请求
                            .cacheMode(CacheMode.NO_CACHE)    // 缓存模式，详细请看缓存介绍
                            .execute(new StringCallback() {

                                @Override
                                public void onSuccess(String s, Call call, Response response) {
                                    // s 即为所需要的结果
                                    Logger.d("网络加载成功，加载搜索数据：" + s);
                                    searchData(s);
                                }

                                @Override
                                public void onError(Call call, Response response, Exception e) {
                                    super.onError(call, response, e);
                                    Toast.makeText(HomeActivity.this, "请检查网络", Toast.LENGTH_SHORT).show();
                                }
                            });
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    /**
     * 获取数据，更新数据
     */
    public void updateData() {
        Logger.d("获取数据");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //currentMillis = System.currentTimeMillis();
                    Response response = OkGo.get(URLs.getDailyDatas(stockNums))//
                            .tag(this)//
                            .execute();
                    String result = response.body().string();
                    Logger.d(URLs.getDailyDatas(stockNums) + "\n"
                            + "网络加载成功，更新数据：" + result);
                    if (result.charAt(0) == '{' && result.charAt(result.length() - 1) == '}') {
                        DailyDataBean dailyDataBean = gson.fromJson(result, DailyDataBean.class);
                        if (dailyDataBean != null && dailyDataBean.errorMsg.equals(ERROR_MSG)
                                && dailyDataBean.data != null) {
                            for (int i=0;i < dailyDataBean.data.size();i++){
                                if (mDailyDataBean != null && mDailyDataBean.data != null
                                        && i < mDailyDataBean.data.size()
                                        && mDailyDataBean.data.get(i) != null) {
                                    double prePrice = mDailyDataBean.data.get(i).close;
                                    double increase = dailyDataBean.data.get(i).close - prePrice;
                                    if (increase > 0) {
                                        dailyDataBean.data.get(i).isRed = 1;
                                    } else if (increase < 0) {
                                        dailyDataBean.data.get(i).isRed = -1;
                                    }
                                }
                            }
                            mDailyDataBean = dailyDataBean;
                        }
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (mStockListAdapter == null) {
                                mStockListAdapter = new StockListAdapter(HomeActivity.this, stockNums, mDailyDataBean);
                                mRvStock.setAdapter(mStockListAdapter);
                            }else {
                                mStockListAdapter = new StockListAdapter(HomeActivity.this, stockNums, mDailyDataBean);
                                mRvStock.swapAdapter(mStockListAdapter, false);
                            }

                            mStockListAdapter.setOnItemClickListener(new StockListAdapter.OnRecyclerViewItemClickListener() {
                                @Override
                                public void onItemClick(View view, int position) {
                                    Logger.d("点击了：" + stockNums.get(position));
                                    Intent intent = new Intent(HomeActivity.this, StockDetailActivity.class);
                                    intent.putExtra("num", stockNums.get(position));
                                    startActivity(intent);
                                }

                                @Override
                                public void onItemLongClick(View view, int position) {

                                }
                            });
                            //返回-1：9:15-11:30, 13:00-15:00, 中国股市交易时间
                            //返回0: 15:00之后，不再更新数据
                            //返回延时时间Min:9:15之前，或者11:30-13:00
                            int delayTime = TimeUtils.delayStockTime();
                            Logger.d(delayTime);
                            mHandler.sendEmptyMessageDelayed(HANDL_MSG_UPDATA, TIMER_INTERVAL);
//                            if (delayTime == -1) {
//                                mHandler.sendEmptyMessageDelayed(HANDL_MSG_UPDATA, TIMER_INTERVAL);
//                            } else if (delayTime == 0) {
//
//                            } else {
//                                mHandler.sendEmptyMessageDelayed(HANDL_MSG_UPDATA, delayTime * 60 * 1000);
//                            }
                            //Logger.e((System.currentTimeMillis() - currentMillis)+"");
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }


    public void addStockNum(String mStockNum, String mStockName) {
        if (stockNums.contains(mStockNum)) {
            return;
        }
        stockNums.add(mStockNum);
        SharePreferenceUtils.putStringList(STOCK_NUM, stockNums, HomeActivity.this);
        mDailyDataBean.data.add(new DailyDataBean.DataBean());
        mStockListAdapter.notifyDataSetChanged();
    }

    public void removeStockNum(int position) {
        stockNums.remove(position);
        SharePreferenceUtils.putStringList(STOCK_NUM, stockNums, HomeActivity.this);
        mDailyDataBean.data.remove(position);
        mStockListAdapter.notifyDataSetChanged();
    }

    public void searchData(String result) {
        if (result.charAt(0) == '{' && result.charAt(result.length() - 1) == '}') {
            mSearchResultBean = gson.fromJson(result, SearchResultBean.class);
            if (mSearchResultBean != null && mSearchResultBean.errorMsg.equals(ERROR_MSG)
                    && mSearchResultBean.data != null && mSearchResultBean.data.stock_data.size() >= 0) {
                Logger.e("mSearchResultBean不为空");
                if (mSearchAdapter == null) {
                    mSearchAdapter = new SearchAdapter(HomeActivity.this, mSearchResultBean);
                    mRvSearch.setAdapter(mSearchAdapter);
                } else {
                    mSearchAdapter = new SearchAdapter(HomeActivity.this, mSearchResultBean);
                    mRvSearch.swapAdapter(mSearchAdapter, false);
                }

                mSearchAdapter.setOnItemClickListener(new SearchAdapter.OnRecyclerViewItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        Logger.d("点击了mSearchResultBean:"
                                + mSearchResultBean.data.stock_data.get(position).f_symbolName);
                        addStockNum(mSearchResultBean.data.stock_data.get(position).f_code
                                , mSearchResultBean.data.stock_data.get(position).f_symbolName);
                        mEtStockNum.setText("");
                        mRvSearch.setVisibility(View.GONE);
                    }

                    @Override
                    public void onItemLongClick(View view, int position) {

                    }
                });
            } else {
                Logger.e("mSearchResultBean为空");
            }
        }
    }

    private long mExitTime = 0;

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - mExitTime > 2000) {
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            mHandler.removeCallbacksAndMessages(null);
            finish();
        }
    }

}
